<?php

/**
 * 附件模型
 */
if ( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );

class Attachment_model extends MY_Model
{

    public $_table = array(
        'attachment' => 'attachment',
        'post_attach' => 'post_attach',
    );
    public $_fields = array(
        'attachment' => array(
            'id' => 'id',
            'name' => 'name',
            'path' => 'path',
            'suffix' => 'suffix',
            'size' => 'size',
            'addtime' => 'addtime',
            'isimage' => 'isimage',
        ),
        'post_attach' => array(
            'postid' => 'postid',
            'attachid' => 'attachid',
        ),
    );

    /**
     * 插入附件数据
     * @param array $data 附件数据
     * @return int 附件ID
     */
    public function add( $data )
    {
        $insertData = array(
            'name' => $data['file_name'],
            'path' => trim( trim( config_item( 'upload_path' ), '.' ), '/' ) . '/',
            'suffix' => trim( $data['file_ext'], '.' ),
            'size' => $data['file_size'],
            'addtime' => time(),
            'isimage' => $data['is_image'],
        );
        $this->db->insert( $this->_table['attachment'], $insertData );
        return $this->insert_id();
    }

    /**
     * 根据信息ID获取相应的图片
     * @param int $postId 信息ID
     * @return array
     */
    public function getByPostId( $postId )
    {
        return $this->db->select( 'a.id,a.name,a.path,a.size,a.addtime,a.isimage' )
                        ->from( "{$this->_table['attachment']} as a" )
                        ->join( "{$this->_table['post_attach']} as pa", 'pa.attachid=a.id' )
                        ->where( 'pa.postid', $postId )
                        ->get()
                        ->row_array();
    }

    public function deleteById( $attachId )
    {
        return $this->db->where('id', $attachId)->delete($this->_table['attachment']);
    }
    
}

?>
